/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.auth.shiro.handlers;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.web.handler.UnauthorizedHandler;
import org.apache.shiro.web.util.WebUtils;
import org.zfes.snowy.core.exceptions.AppRuntimeException;
import org.zfes.snowy.core.util.ZStrUtil;

public abstract class AbstractAuthorizHandler implements UnauthorizedHandler{
	
	
	public void onUnauthorized(HttpServletRequest request,HttpServletResponse response)throws IOException{
		//to do nothing	
	}
	protected boolean forwardToDestination = false;
	
	
	protected void saveRequestAndRedirect(ServletRequest request, ServletResponse response,String url) throws IOException {
		  saveRequest(request);
		  redirectUnauthorizedUrl(request, response,url);
		}
		
	protected void saveRequestAndForward(ServletRequest request, ServletResponse response,String url) throws IOException {
			  saveRequest(request);
			  redirectUnauthorizedUrl(request, response,url);
		}
		
	protected void saveRequest(ServletRequest request) {
		  WebUtils.saveRequest(request);
		}
		
	protected void redirectUnauthorizedUrl(ServletRequest request, ServletResponse response,String url) throws IOException {
			if(!ZStrUtil.hasText(url)){
				throw new AppRuntimeException("没有配置未授权页面");
			}
		  WebUtils.issueRedirect(request, response, url);
		}
	   protected void forWordToLogin(ServletRequest request, ServletResponse response,String url) throws IOException {
			if(!ZStrUtil.hasText(url)){
				throw new AppRuntimeException("未配置未授权页面");
			}
		  WebUtils.issueRedirect(request, response, url);
		}

		public boolean isForwardToDestination() {
			return forwardToDestination;
		}
	
		public void setForwardToDestination(boolean forwardToDestination) {
			this.forwardToDestination = forwardToDestination;
		}
	
}
